package com.maori.languageapp;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;
import android.widget.AdapterView.OnItemClickListener;
import com.maori.languageapp.R;
import com.maori.languageapp.adapter.LanguageAppDialetDataList;
import com.maori.languageapp.adapter.Language_App_List_Exapander;
import com.maori.languageapp.adapter.Maori_NavDrawerListAdapter;
import com.maori.languageapp.fragments.Maori_Main_Fragment;
import com.maori.languageapp.model.Maori_NavDrawerItem;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class Maori_Capture_Word extends FragmentActivity {
	// private PBDatabaseAdapter dbHelper;
	ProgressDialog mProgressDialog;
	HttpParams httpParameters = new BasicHttpParams();
	int timeoutConnection = 5000;
	int NCMID;
	String node_category, CurrentCategory, node_category_id;
	String type;
	EditText etmaoriword, etenglishword, etvideo;
	Button record_button, play_button, camera_button, gallery_button,
			submitbtn, cancelbtn;
	InputStream is = null;
	StringBuilder sb = null;
	String result = null;
	private MediaRecorder myRecorder;
	int recordActive = 0;
	int recordPlay = 0;
	private MediaPlayer myPlayer;
	private String outputFile = null;
	ImageView ivThumbnailPhoto;
	ListView rdgrp;
	private static final int CAMERA_PIC_REQUEST = 2500;
	int dialectidhere;
	Bitmap bitMap;
	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;
	private CharSequence mDrawerTitle;
	private CharSequence mTitle;
	private String[] navMenuTitles;
	private TypedArray navMenuIcons;
	private ArrayList<Maori_NavDrawerItem> navDrawerItems;
	private Maori_NavDrawerListAdapter adapter;
	String CurrentTypeOfCapture, content_type_id;
	private Spinner spinnerTypeOfCapture, spinnerCategory;
	private ArrayAdapter<CharSequence> m_adapterForSpinnerTC;
	private ArrayAdapter<CharSequence> m_adapterForSpinnerCat;
	private static final int PICK_IMAGE = 1;
	// Database Name
	private static final String DATABASE_NAME = "maorilanguageapp.db";
	protected static final String TAG = null;
	// Master Tables
	private String USER_TABLE = "User";
	private String CONTENTTYPE_TABLE = "Content_type";
	private String DIALACT_TABLE = "Dialact";
	private String LANGUAGE_TABLE = "Language";
	private String MEDIA_TABLE = "Media";
	private String NODECATEGORY_TABLE = "Node_Category";
	private String PHRASE_TABLE = "Phrase";
	private String SONG_TABLE = "Song";
	private String STORY_TABLE = "Story";
	private String WORD_TABLE = "Word";
	private SQLiteDatabase mydb;
	int DialetPasition;
	private RadioButton listRadioButton = null;
	int listIndex = -1;
    private ListView listView;
    private List<LanguageAppDialetDataList> rowItems;
    LanguageAppDialetDataList DialetListData;
    LanguageAppDialetAdapterList DialectAdapter;
	private static int RESULT_LOAD_IMAGE = 1;
	LinearLayout capturewordblock;
	Uri selectedImageUri;
	byte[] data;
	String filemanagerstring;
	String selectedImagePath;
	String filePath;
	private Bitmap bitmap;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.maori_activity_capture_word);

		// /PSJ - Code To Add Drawer

		mTitle = mDrawerTitle = getTitle();

		navMenuTitles = getResources().getStringArray(
				R.array.maori_nav_drawer_items);

		navMenuIcons = getResources().obtainTypedArray(
				R.array.maori_nav_drawer_icons);

		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout_cap_word);
		mDrawerList = (ListView) findViewById(R.id.list_slidermenu_cap_word);

		navDrawerItems = new ArrayList<Maori_NavDrawerItem>();

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[0],
				navMenuIcons.getResourceId(0, -1)));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[1],
				navMenuIcons.getResourceId(1, -1)));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[2],
				navMenuIcons.getResourceId(2, -1)));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[3],
				navMenuIcons.getResourceId(3, -1), true, "22"));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[4],
				navMenuIcons.getResourceId(4, -1)));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[5],
				navMenuIcons.getResourceId(5, -1), true, "50+"));

		navMenuIcons.recycle();

		mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

		adapter = new Maori_NavDrawerListAdapter(getApplicationContext(),
				navDrawerItems);
		mDrawerList.setAdapter(adapter);

		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);
		getActionBar().setBackgroundDrawable(
				new ColorDrawable(Color.parseColor("#0d284c")));

		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.menubutton, R.string.app_name, R.string.app_name) {
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
				invalidateOptionsMenu();
			}

			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle(mDrawerTitle);
				invalidateOptionsMenu();
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			NCMID = extras.getInt("NCMID");
			node_category = extras.getString("node_category");
			type = extras.getString("type");
		}
		EditText EtType = (EditText) findViewById(R.id.ettypeofcapture);
		EditText EtCat = (EditText) findViewById(R.id.etselectcategory);

		// Get Values From EditText Values
		etmaoriword = (EditText) findViewById(R.id.etmaoriword);
		etenglishword = (EditText) findViewById(R.id.etenglishword);
		etvideo = (EditText) findViewById(R.id.etvideo);

		// Button View Controllers
		record_button = (Button) findViewById(R.id.record_button);
		play_button = (Button) findViewById(R.id.play_button);
		camera_button = (Button) findViewById(R.id.camera_button);
		gallery_button = (Button) findViewById(R.id.gallery_button);

		// Submit Word Details To Server
		submitbtn = (Button) findViewById(R.id.submitbtn);
		submitbtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				new UploadingWordsDetails().execute();
			}
		});

		// Cancel Current View and Exit
		cancelbtn = (Button) findViewById(R.id.cancelbtn);
		cancelbtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				displayCancelDialog();
			}
		});

		// Recording Audio
		record_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				if (recordActive == 0) {
					recordActive = 1;
					// Audio Recording
					// store it to sd card
					record_button.setBackground(getResources().getDrawable(R.drawable.recordstop_button));
					outputFile = Environment.getExternalStorageDirectory()
							.getAbsolutePath() + "/"+getAudiorecording().toString()+ ".3gpp";
					myRecorder = new MediaRecorder();
					myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
					myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
					myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
					myRecorder.setOutputFile(outputFile);
					Log.v(TAG, "AUDIO PATH : "+ outputFile);
					play_button.setEnabled(false);
					start(view);
				} else if (recordActive == 1) {
					recordActive = 0;
					record_button.setBackground(getResources().getDrawable(R.drawable.record_button));
					play_button.setEnabled(true);
					stop(view);
				}

			}
		});

		// Play Current Recoring
		play_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if (recordPlay == 0) {
					recordPlay = 1;
					play_button.setBackground(getResources().getDrawable(R.drawable.playstop_button));
					record_button.setEnabled(false);
					recordPlay(view);
				} else if (recordPlay == 1) {
					recordPlay = 0;
					play_button.setBackground(getResources().getDrawable(R.drawable.play_button));
					record_button.setEnabled(true);
					stopPlay(view);
				}

			}
		});

		// Launch Camera
		ivThumbnailPhoto = (ImageView) findViewById(R.id.ImageView01);
		camera_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				// create intent with ACTION_IMAGE_CAPTURE action
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(intent, CAMERA_PIC_REQUEST);
			}
		});

		gallery_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				try {
					Intent intent = new Intent();
					intent.setType("image/*");
					intent.setAction(Intent.ACTION_GET_CONTENT);
					startActivityForResult(
							Intent.createChooser(intent, "Select Picture"),
							PICK_IMAGE);

				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), e.getMessage(),
							Toast.LENGTH_LONG).show();
					Log.e(e.getClass().getName(), e.getMessage(), e);
				}

			}
		});
		
		
		
		spinnerTypeOfCapture = (Spinner) findViewById(R.id.spinnerTypeOfCapture);
		spinnerCategory = (Spinner) findViewById(R.id.spinnerCategory);
		loadTypeOfCapture();
		loadCategory();
		//loadDialectList();
		loadDialectListView();

		spinnerTypeOfCapture.setAdapter(m_adapterForSpinnerTC);
		spinnerTypeOfCapture
				.setOnItemSelectedListener(new OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int position, long id) {
						CurrentTypeOfCapture = spinnerTypeOfCapture
								.getSelectedItem().toString();
						if (!(CurrentTypeOfCapture.equals("SELECT SERVER DB"))) {

							SQLiteDatabase mydb;
							mydb = openOrCreateDatabase(DATABASE_NAME,
									Context.MODE_PRIVATE, null);

							Cursor getfromloccur = null;
							try {
								getfromloccur = mydb.query(CONTENTTYPE_TABLE,
										null, "content='"
												+ CurrentTypeOfCapture + "'",
										null, null, null, null, null);
							} catch (Exception e) {

							}
							if (getfromloccur != null) {
								if (getfromloccur.getCount() > 0) {
									while (getfromloccur.moveToNext()) {
										content_type_id = getfromloccur
												.getString(1);
										type = getfromloccur.getString(2);
										Log.v(TAG, "Capture :"+ content_type_id +" = "+type);
									}
								}
								getfromloccur.close();
							}
							// m_adapterForSpinnerTC.add(type);

						} else {
						}

					}

					public void onNothingSelected(AdapterView<?> parent) {
					}
				});

		spinnerCategory.setAdapter(m_adapterForSpinnerCat);
		spinnerCategory.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				CurrentCategory = spinnerCategory.getSelectedItem().toString();
				if (!(CurrentCategory.equals("SELECT SERVER DB"))) {

					SQLiteDatabase mydb;
					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);

					Cursor getFromCategory = null;
					try {
						getFromCategory = mydb.query(NODECATEGORY_TABLE, null,
								"node_category='" + CurrentCategory + "'",
								null, null, null, null, null);
					} catch (Exception e) {

					}
					if (getFromCategory != null) {
						if (getFromCategory.getCount() > 0) {
							while (getFromCategory.moveToNext()) {
								node_category_id = getFromCategory.getString(1);
								node_category = getFromCategory.getString(2);
								Log.v(TAG, "Category :"+ node_category_id +" = "+node_category);
							}
						}
						getFromCategory.close();
					}
					// m_adapterForSpinnerTC.add(type);

				} else {
				}

			}

			public void onNothingSelected(AdapterView<?> parent) {
			}
		});

	}

	
	
	private void loadDialectListView() {
		// TODO Auto-generated method stub
		rowItems = new ArrayList<LanguageAppDialetDataList>();
		 // DialetListData/DialectAdapter
        mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor curListDialect = null;
		try {
			String querySelectDebtor = "SELECT * FROM Dialact";
			curListDialect = mydb.rawQuery(querySelectDebtor, null);
		} catch (Exception e) {
		}
		if (curListDialect != null) {
			if (curListDialect.getCount() > 0) {
				while (curListDialect.moveToNext()) {
					String dialectid = curListDialect.getString(1);
					String dialectname = curListDialect.getString(2);
					DialetListData = new LanguageAppDialetDataList(dialectid, dialectname);
			        rowItems.add(DialetListData);
				}
			}
		}
        
        listView = (ListView) findViewById(R.id.listdialect);
        DialectAdapter=new LanguageAppDialetAdapterList(this, R.layout.language_app_dialect_listview_raw, rowItems);
        listView.setAdapter(DialectAdapter);
        //Language_App_List_Exapander.getListViewSize(listView);
        curListDialect.close();
		mydb.close();
		
	}
	
	public void onRadioButtonClicked(View view) {
	    // Is the button now checked?
	    boolean checked = ((RadioButton) view).isChecked();
	    Toast toast = new Toast(getApplicationContext());
	    toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
	    toast.setDuration(Toast.LENGTH_LONG);
	    toast.setText("RADIO CLICK :"+checked);
	    toast.show();
	}
	private void loadCategory() {
		// TODO Auto-generated method stub
		m_adapterForSpinnerCat = new ArrayAdapter<CharSequence>(this,
				android.R.layout.simple_spinner_item);
		m_adapterForSpinnerCat
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor curNodeCategory = null;
		try {
			curNodeCategory = mydb.query(NODECATEGORY_TABLE, null, null, null,
					null, null, null, null);
		} catch (Exception e) {
		}
		if (curNodeCategory != null) {
			if (curNodeCategory.getCount() > 0) {
				m_adapterForSpinnerCat.add(node_category);
				while (curNodeCategory.moveToNext()) {
					m_adapterForSpinnerCat.add(curNodeCategory.getString(2));
				}
			}
			curNodeCategory.close();
		}
		mydb.close();
	}

	private void loadTypeOfCapture() {
		// TODO Auto-generated method stub
		m_adapterForSpinnerTC = new ArrayAdapter<CharSequence>(this,
				android.R.layout.simple_spinner_item);
		m_adapterForSpinnerTC
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor curContentType = null;
		try {
			curContentType = mydb.query(CONTENTTYPE_TABLE, null, null, null,
					null, null, null, null);
		} catch (Exception e) {
		}
		if (curContentType != null) {
			if (curContentType.getCount() > 0) {
				m_adapterForSpinnerTC.add(type);
				while (curContentType.moveToNext()) {
					m_adapterForSpinnerTC.add(curContentType.getString(2));
				}
			}
			curContentType.close();
		}
		mydb.close();
	}

	protected void stopPlay(View view) {
		// TODO Auto-generated method stub
		try {
			if (myPlayer != null) {
				myPlayer.stop();
				myPlayer.release();
				myPlayer = null;
				Toast.makeText(getApplicationContext(),
						"Stop playing the recording...", Toast.LENGTH_SHORT)
						.show();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// Play Current Audio
	protected void recordPlay(View view) {
		// TODO Auto-generated method stub
		try {
			myPlayer = new MediaPlayer();
			myPlayer.setDataSource(outputFile);
			myPlayer.prepare();
			myPlayer.start();
			Toast.makeText(getApplicationContext(),
					"Start play the recording...", Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// Stop Playing Audio
	protected void stop(View view) {
		// TODO Auto-generated method stub
		try {
			myRecorder.stop();
			myRecorder.release();
			myRecorder = null;
			Toast.makeText(getApplicationContext(), "Stop recording...",
					Toast.LENGTH_SHORT).show();
		} catch (IllegalStateException e) {
			// it is called before start()
			e.printStackTrace();
		} catch (RuntimeException e) {
			// no valid audio/video data has been received
			e.printStackTrace();
		}
	}

	// Start Playing Audio
	protected void start(View view) {
		// TODO Auto-generated method stub
		try {
			myRecorder.prepare();
			myRecorder.start();
			Toast.makeText(getApplicationContext(), "Start recording...",
					Toast.LENGTH_SHORT).show();
		} catch (IllegalStateException e) {
			// start:it is called before prepare()
			// prepare: it is called after start() or before setOutputFormat()
			e.printStackTrace();
		} catch (IOException e) {
			// prepare() fails
			e.printStackTrace();
		}
		/*
		 * startBtn.setEnabled(false); stopBtn.setEnabled(true);
		 */
	}

	protected void displayCancelDialog() {
		// TODO Auto-generated method stub
		AlertDialog.Builder builder = new AlertDialog.Builder(
				Maori_Capture_Word.this);
		builder.setTitle("CANCEL");
		builder.setMessage("Are Sure You Want To Exit...");
		builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				Intent myIntent = new Intent(getBaseContext(),
						Maori_MainActivity.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
			}
		});
		builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(),
						"Add New Words Details..", Toast.LENGTH_LONG).show();
			}
		});
		builder.show();
	}

	private class UploadingWordsDetails extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(Maori_Capture_Word.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Uploading");
			// Set progressdialog message
			mProgressDialog.setMessage("Uploading Word Details");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();

		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(
						"http://langapp.testarea.co.nz/lanappwak/saveMaoriWords.php");
				JSONObject json = new JSONObject();
				json.put("record1", "1"); // content_type_id
				json.put("record2", "1"); // added_by
				json.put("record3", getAddDateTimeString().toString()); // added_on
				json.put("record4", "1"); // updated_by
				json.put("record5", getAddDateTimeString().toString()); // updated_on
				json.put("record6", "1"); // dialect_id
				json.put("record7", NCMID); // node_cat_id
				json.put("record8", "1=2"); // LID
				json.put("record9", etenglishword.getText().toString()+"="+etmaoriword.getText().toString()); // word
				json.put("record10", "1"); // MID
				json.put("record11", etvideo.getText().toString()); // M_Source

				JSONArray postjson = new JSONArray();
				postjson.put(json);

				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				Log.e("postjson", "postjson :" + postjson.toString());

				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {

					}
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			mProgressDialog.dismiss();
			final AlertDialog alertDialog = new AlertDialog.Builder(
					Maori_Capture_Word.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("DATA ULOADED");
			// Setting Dialog Message
			alertDialog.setMessage("Words Details Data Upload Completed...");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					Intent myIntent = new Intent(getBaseContext(),
							Maori_MainActivity.class);
					myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
							| Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivityForResult(myIntent, 0);
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;

		}

	}

	private class SlideMenuClickListener implements
			ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			LinearLayout lnlar = (LinearLayout) findViewById(R.id.cap_word_linear);
			lnlar.setVisibility(View.GONE);
			displayView(position);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);

		MenuItem searchItem = menu.findItem(R.id.search);
		SearchView searchView = (SearchView) MenuItemCompat
				.getActionView(searchItem);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}

		switch (item.getItemId()) {
		case R.id.action_settings:
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {

		boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
		menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	private void displayView(int position) {
		Fragment fragment = null;
		switch (position) {
		case 0:
			fragment = new Maori_Main_Fragment(0);
			break;
		case 1:
			fragment = new Maori_Main_Fragment(1);
			break;
		case 2:
			fragment = new Maori_Main_Fragment(2);
			break;
		case 3:
			fragment = new Maori_Main_Fragment(0);
			break;
		case 4:
			fragment = new Maori_Main_Fragment(0);
			break;
		case 5:
			fragment = new Maori_Main_Fragment(0);
			break;

		default:
			break;
		}

		if (fragment != null) {
			FragmentManager fragmentManager = getSupportFragmentManager();
			fragmentManager.beginTransaction()
					.replace(R.id.frame_container_cap_word, fragment).commit();

			mDrawerList.setItemChecked(position, true);
			mDrawerList.setSelection(position);
			setTitle(navMenuTitles[position]);
			mDrawerLayout.closeDrawer(mDrawerList);
		} else {
			Log.e("MainActivity", "Error in creating fragment");
		}
	}

	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getActionBar().setTitle(mTitle);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	private String getAddDateTimeString() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	private String getAudiorecording() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyyMMddHHmmss");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}
	public void onBackPressed() {
		super.onBackPressed();
	}

	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case PICK_IMAGE:
			if (resultCode == Activity.RESULT_OK) {
				selectedImageUri = data.getData();

				try {
					// OI FILE Manager
					filemanagerstring = selectedImageUri.getPath();

					// MEDIA GALLERY
					selectedImagePath = getPath(selectedImageUri);

					if (selectedImagePath != null) {
						filePath = selectedImagePath;
					} else if (filemanagerstring != null) {
						filePath = filemanagerstring;
					} else {
						Toast.makeText(getApplicationContext(), "Unknown path",
								Toast.LENGTH_LONG).show();
						Log.e("Bitmap", "Unknown path");
					}

					if (filePath != null) {
						decodeFile(filePath);
					} else {
						bitmap = null;
					}
				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "Internal error",
							Toast.LENGTH_LONG).show();
					Log.e(e.getClass().getName(), e.getMessage(), e);
				}
			}
		case CAMERA_PIC_REQUEST:
			if (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK && data != null) {
		// get bundle
		Bundle extras = data.getExtras();

		// get
		bitMap = (Bitmap) extras.get("data");
		ivThumbnailPhoto.setImageBitmap(bitMap);

	}
			break;
		default:
		}

	}

	private String decodeFile(String filePath) {
		// Decode image size
		BitmapFactory.Options o = new BitmapFactory.Options();
		o.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, o);

		// The new size we want to scale to
		final int REQUIRED_SIZE = 1024;

		// Find the correct scale value. It should be the power of 2.
		int width_tmp = o.outWidth, height_tmp = o.outHeight;
		int scale = 1;
		while (true) {
			if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
				break;
			width_tmp /= 2;
			height_tmp /= 2;
			scale *= 2;
		}

		BitmapFactory.Options o2 = new BitmapFactory.Options();
		o2.inSampleSize = scale;

		bitmap = BitmapFactory.decodeFile(filePath, o2);
		ivThumbnailPhoto.setImageBitmap(bitmap);
		return filePath;
	}

	private String getPath(Uri selectedImageUri) throws FileNotFoundException {

		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(selectedImageUri, projection, null, null,
				null);

		if (cursor != null) {

			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

			cursor.moveToFirst();
			/* Uri uri = Uri.parse(cursor.getString(1)); */

			return cursor.getString(column_index);
		} else
			return null;
	}
}
